const fs = require('fs');
class api {

    constructor() {
        /*return new Promise((resolve, reject) => {
            fs.readdir(ROOT_DIR + DS + "assets"+DS+"library", function(err, data) {
                let result = [];
                data.forEach(function(value, key) {
                    let name = rtrim(value,'.');
                    result.push(value)
                })
                if (err) {
                    reject(err)
                } else {
                    console.log(result)
                    resolve(result);
                }
            })
        })*/


    }

    get_model() {
        return new Promise((resolve, reject) => {
            fs.readdir(ROOT_DIR + DS + "assets" + DS + "library", function(err, data) {
                let result = [];
                data.forEach(function(value, key) {
                    if (value != 'invite.js') {
                        let name = rtrim(value, '.js');
                        result.push(name)
                    }
                })
                if (err) {
                    reject(err)
                } else {
                    resolve(result);
                }
            })
        })
    }

    async api() {
        try {
            let data = $_POST;
            /*let data = {
                name: "test", //模块名称
                where: {test_name:222},
                order:'_id DESC',
                limit: '0,2',
                field: ['_id'],
                action: "delete", //update delete
                data:{test_name:'wiki',test_sex:'男1'}


            }*/
            let models = await this.get_model();
            if (data.name && in_array(data.name, models)) {
                data.where['_uuid'] == data._uuid;

            } else {
                throw new Exception('没有该模块权限', 10001);
            }

            switch (data.action) {
                case 'select':
                    return await sql.name(data.name).where(data.where).order(data.order).limit(data.limit).page(data.page, data.size).select(data.field);
                    break;
                case 'insert':
                    return await sql.name(data.name).insert(data.data);
                    break;
                case 'update':
                    if (empty(data.where)) {
                        return false;
                    }
                    return await sql.name(data.name).where(data.where).update(data.data);
                    break;
                case 'delete':
                    if (empty(data.where)) {
                        return false;
                    }
                    return await sql.name(data.name).where(data.where).delete();
                    break;
                case 'first':
                    return await sql.name(data.name).where(data.where).first();
                    break;
            }
        } catch (error) {
            throw new Exception(error);
        }
    }

}


module.exports = api;